﻿using NPOI.ReadExcel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;

namespace ExtractPhotos
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        } 
         
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // 在WPF中， OpenFileDialog位于Microsoft.Win32名称空间
            Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog();
            dialog.Filter = "Excel文件|*.xlsx";
            if (dialog.ShowDialog() == true)
            {
                excel.Text = dialog.FileName;
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog();
            dialog.Filter = "txt文件|*.txt";
            if (dialog.ShowDialog() == true)
            {
                txt.Text = dialog.FileName; 
            }
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
        

            //读取txt文件的内容
            var txt = ReadTxt();
            var c1 =  int.Parse(string.IsNullOrEmpty(cel1.Text)?"2": cel1.Text)-1; //身份证
            var c2 = int.Parse(string.IsNullOrEmpty(cel2.Text)?"3":cel2.Text)-1; //标记
            var dir = Path.GetDirectoryName(excel.Text)+"\\"+ DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xls";
            if (excel.Text.IndexOf(".xlsx") > 0)
            {
                dir += ".xlsx";
            }
            else
            {
                dir += ".xls";
            }

            if (txt.Count <= 0)
            {
                MessageBox.Show("没有数据需要处理");
                return;
            };

            //读取excel文件
            var dataTable =  new ExcelHelper(excel.Text).ExcelToDataTable("Sheet1",true);
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
               var row = dataTable.Rows[i];
                var id = row[c1].ToString();  //身份证
                if (txt.Contains(id)) //存在没有图片的数据
                {
                    row[c2] = "无照片";
                    //移除数据
                    txt.Remove(id);
                    if (txt.Count <= 0)
                    {
                        break;
                    }
                }
            }

            new ExcelHelper(dir).DataTableToExcel(dataTable,"Sheet",true);

            MessageBox.Show("程序已经处理完成");
        }

        private List<string> ReadTxt()
        {
            System.IO.StreamReader sr = System.IO.File.OpenText(txt.Text); 
            var result = sr.ReadToEnd().Replace("\r\n","").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();  
            sr.Close();
            return result;
        }
    }
}
